package com.sfang.common.extension;

import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import com.sfang.common.base.dingtalk.DingTalkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@Component
public class CustomP6spyInterceptor implements MessageFormattingStrategy {

    @Resource
    Environment environment;

    @Value("${spring.application.name:}")
    private String applicationName;
    private static String appKey;
    private static String env;

    @Autowired(required = false)
    private HttpServletRequest request;

    @PostConstruct
    public void init() {
        appKey = applicationName;

        if (environment != null && environment.getProperty("env") != null)
            env = environment.getProperty("env");
        else if (environment != null && environment.getProperty("spring.cloud.config.profile") != null)
            env = environment.getProperty("spring.cloud.config.profile");
        else
            env = "none";
    }

    @Override
    public String formatMessage(int connectionId, String now, long elapsed,
                                String category, String prepared, String sql, String url) {

        String message = String.format("MybatisInterceptor SQL：[%s]执行耗时[%sms])",
                sql,
                elapsed);

        if (env != null
                && (env.equalsIgnoreCase("prod") || env.equalsIgnoreCase("uat"))
                && elapsed >
                (environment.getProperty("sql.elapsed.threshold") != null
                        ? Integer.parseInt(Objects.requireNonNull(environment.getProperty("sql.elapsed.threshold")))
                        : 1500)) {

            message=String.format("MybatisInterceptor Slow SQL：[%s]执行耗时[%sms])",
                    sql,
                    elapsed);

            if (environment.getProperty("sql.dingtalk.enabled") != null && Boolean.parseBoolean(environment.getProperty("sql.dingtalk.enabled")))
                try {
                  String  messageDingTalk = String.format("【慢sql报警|" + appKey + "|" + env + "】\nurl-%s \ntraceId-%s \n%s执行耗时[%sms]",
                            (request == null ? "" : request.getRequestURL()),
                            (request == null ? "" : request.getHeader("traceId")),
                            sql,
                            elapsed);

                    log.info(String.format("MybatisInterceptor slow sql send dingTalk message：%s)", messageDingTalk));

                    DingTalkUtil.send(messageDingTalk,
                            "https://oapi.dingtalk.com/robot/send?access_token=7d826f1947b4edabcf3ae083fd3e51873d5f6c8793da21d4fe8b97f99be7c853");
                    log.info(String.format("MybatisInterceptor slow sql send dingTalk message success：%s)", messageDingTalk));

                } catch (Exception e) {
                    log.error("MybatisInterceptor slow sql error", e);
                }
        }

        return message;
    }
}

